﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FTPLib;
using System.IO;
using System.ComponentModel;
using System.Net.Sockets;

namespace Awesome_FTPlib
{
   public class UploadWorker
    {
       private FTP TheFTP;
       public FileInfo File { get; set; }
       private BackgroundWorker BW;
       private double div;
       private string RemotePath;

       private FileStream FileStream;

       private Socket Datasocket;
       private Socket ListeningSocket;
       private long _TotalBytes = 0;

       public UploadWorker(FTP FTP, string LocalPath, string Remotepath)
       {
           TheFTP = FTP;
           RemotePath = Remotepath;
   
           File = new FileInfo(LocalPath);
           //FileStream = new FileStream(LocalPath, FileMode.Open);
           BW = new BackgroundWorker();
           BW.WorkerSupportsCancellation = false;
           BW.WorkerReportsProgress = true;
           BW.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BW_RunWorkerCompleted);
           BW.ProgressChanged += new ProgressChangedEventHandler(BW_ProgressChanged);
           BW.DoWork += new DoWorkEventHandler(BW_DoWork);

       }

       public void Start()
       {
           string CurrentPath = FTPClient.CurrentPath;
           if (RemotePath != FTPClient.CurrentPath)
           {
               
               TheFTP.ChangeDir(FTPClient.CurrentPath, RemotePath);
               
           }
           Datasocket = TheFTP.OpenUpload(File.FullName, File.Name, ref FileStream, false);
           if (BW.IsBusy != true)
           {
               
               BW.RunWorkerAsync();

           }
           if (RemotePath != CurrentPath)
           {
               TheFTP.ChangeDir(RemotePath, FTPClient.CurrentPath);
           }
       }

       void BW_DoWork(object sender, DoWorkEventArgs e)
       {
           while (TheFTP.DoUpload(Datasocket,FileStream, ref _TotalBytes) > 0)
           {



               div = (int)(((_TotalBytes) * 100) / TheFTP.FileSize);
             
               BW.ReportProgress((int)div);
           }
       }

       void BW_ProgressChanged(object sender, ProgressChangedEventArgs e)
       {
           //throw new NotImplementedException();
           Console.WriteLine(this.File.Name + ": " +div + " %" );
       }

       void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
       {
           Console.WriteLine("Done!" );
       }

    }
}
